/**
 * Convert Yaml files to PlantUml files.
 *
 * Usage:
 * kotlin yml_to_puml.main.kts <input_file_path> <output_file_path>
 *
 * IDEA File Watcher Usage:
 * Scope - file:*.puml.yml
 * Program - C:\Windows\System32\WindowsPowerShell\v1.0\powershell
 * Arguments - kotlin yml_to_puml.main.kts '$FilePath$' '$FileDir$\generated\$FileNameWithoutExtension$'
 *
 * @author DragonKnightOfBreeze
 */

@file:DependsOn("com.fasterxml.jackson.module:jackson-module-kotlin:2.10.1")
@file:DependsOn("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.10.1")

import com.fasterxml.jackson.dataformat.yaml.*
import com.fasterxml.jackson.module.kotlin.*
import java.io.*

//得到输入的yml文件的路径
val inputFilePath = args.getOrElse(0) {
	throw IllegalArgumentException("Argument 'input_file_path' cannot be null.")
}
//得到输出的yml文件的路径，如果没有，则使用输入文件的路径
val outputFilePath = args.getOrElse(1) {
	inputFilePath.replace(".yml", "")
}

val mapper = YAMLMapper()
//得到yml文件结构
val data = mapper.readValue<Map<*, *>>(File(inputFilePath))

//递归转化为对应的puml文本
val text = """
''Generated By yml_to_puml.main.kts

@startuml
${data.toPumlText()}
@enduml
""".trimIndent()

val file = File(outputFilePath)
file.parentFile.mkdirs()
file.writeText(text)

fun Any?.toPumlText(): String {
	return when {
		this == null -> ""
		this is Map<*, *> -> this.entries.joinToString("\n") { (k, v) ->
			if(v == "") "$k" else "$k {\n${v.toPumlText().prependIndent("  ")}\n}"
		}
		this is List<*> -> this.joinToString("\n") { e ->
			e.toPumlText()
		}
		else -> this.toString()
	}
}
